package seqlist.link.leetcode;

/**
 * @author yuisama
 * @date 2023/03/19 10:20
 * 链表倒数第k个节点
 **/
public class NowCoder_KthNode {
    public ListNode FindKthToTail(ListNode head,int k) {
        // 1.base case
        if (head == null || k <= 0) {
            return null;
        }
        ListNode fir = head,sec = head;
        // 先让fir走k步
        for (int i = 0; i < k; i++) {
            if (fir == null) {
                // 此时k > 链表长度
                return null;
            }
            fir = fir.next;
        }
        // 此时fir和sec开始同时向后遍历
        while (fir != null) {
            sec = sec.next;
            fir = fir.next;
        }
        return sec;
    }
}